package org.example.demoarticle.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

public class jwtUtil {
    private static String signKey="xiaowuz";
    private static Long expire=43200000L;

    /**
     * 生成jwt令牌
     * @param claims
     * @return
     */
    public static String generateJwt (Map<String,Object> claims) {
        String jwt= Jwts.builder()
                .addClaims(claims)
                .signWith(SignatureAlgorithm.HS256,signKey)
                .setExpiration(new Date(System.currentTimeMillis()+expire))
                .compact();
        return jwt;
    }

    /**
     * 解析jwt令牌
     * @param jwt
     * @return
     */
    public static Claims parseJwt(String jwt) {
        Claims claims=Jwts.parser()
                .setSigningKey(signKey)
                .parseClaimsJws(jwt)
                .getBody();
        return claims;
    }

    public static String getUsernameByJwt(String jwt) {
        Claims claims=parseJwt(jwt);
        return (String) claims.get("userName");
    }
}
